//
//  goveDetailVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/5/20.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "goveDetailVC.h"
#import "goveCell.h"
#import "areaEncyclopediasVC.h"
#import "goveNewsVC.h"
#import "projectLibraryVC.h"
#import "newsDetailVC.h"
#import "FriendViewController.h"
#import "TrickTender.h"

static NSString *identifier =@"cellIdentifier";
@interface goveDetailVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *headImg;
@property (weak, nonatomic) IBOutlet UILabel *goveName;

@property (weak, nonatomic) IBOutlet UILabel *goveDetail;
@property (strong, nonatomic) NSDictionary *dataDict;
@property (strong, nonatomic) UICollectionView * collectionview;
@property (strong, nonatomic) NSArray *imgArr;
@property (strong, nonatomic) NSString *webStr;

@property (strong, nonatomic) UIButton *rightBtnItem;
@property (assign, nonatomic) BOOL isfocus;
@property (strong, nonatomic) UIImageView *lineView;
@end

@implementation goveDetailVC

#pragma mark - 初始化
-(NSArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [NSArray array];
    }
    return _imgArr;
}
-(NSDictionary *)dataDict{
    if (!_dataDict) {
        _dataDict = [NSDictionary dictionary];
    }
    return _dataDict;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];

    self.navigationController.hidesBottomBarWhenPushed  = YES;
    //隐藏导航栏下边的黑线的另一种方法
    self.lineView.hidden = YES;

    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"政府-背景2"] forBarMetrics:UIBarMetricsDefault];
    //隐藏导航栏下边的黑线
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self sendRequest];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"";
    //获取导航栏下面的黑线
    self.lineView = [self getLineViewNavigationBar:self.navigationController.navigationBar];
    
    self.view.backgroundColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1];
         self.imgArr = @[@"频道-地区百科",@"频道-招商项目",@"频道-公开年报",@"频道-产业规划",@"频道-投资政策",@"频道-投资要素",@"频道-服务机构",@"频道-产业规划",@"频道-招商投标",@"频道-商务动态"];
    
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    //关注按钮

    self.rightBtnItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
    [self.rightBtnItem addTarget:self action:@selector(rightBarButtonItemClick:) forControlEvents:UIControlEventTouchUpInside];
    self.rightBtnItem.titleLabel.textAlignment = NSTextAlignmentRight;
    self.rightBtnItem.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtnItem];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    // 设置底部按钮
    
    if (!self.isFlag) {
        NSMutableArray * btnArr = [NSMutableArray array];
        
        for (int i = 0; i < 2; i++) {
            UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(i * screenW/2, screenH - 45, screenW/2, 45)];
            btn.backgroundColor = [UIColor whiteColor];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            [btn setTitleColor:RGB(0, 170, 240) forState:UIControlStateNormal];
            [self.view addSubview:btn];
            [btnArr addObject:btn];
            
        }
        
//        [btnArr[0] setImage:[UIImage imageNamed:@"组-31" ] forState:0];
//        [btnArr[0] setImage:[UIImage imageNamed:@"已关注"] forState:UIControlStateSelected];
        [(UIButton *)btnArr[0] setTitle:@"发私信" forState:UIControlStateNormal];

    
        self.focusBtn = btnArr[0];
        
        [self.focusBtn addTarget:self action:@selector(focus) forControlEvents:UIControlEventTouchUpInside];
//        [btnArr[1] setImage:[UIImage imageNamed:@"组-32" ] forState:0];
        [(UIButton *)btnArr[1] setTitle:@"加好友" forState:UIControlStateNormal];
        self.classBtn = btnArr[1];
        [self.classBtn addTarget:self action:@selector(classbtn) forControlEvents:UIControlEventTouchUpInside];
        //竖小线
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(screenW/2, screenH - 45, 1, 45)];
        lineview.backgroundColor = RGB(235, 235, 235);
        //横小线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, screenH - 45, screenW, 1)];
        lineView.backgroundColor = RGB(235, 235, 235);
        [self.view addSubview:lineview];
        [self.view addSubview:lineView];
    }
    

    
    [self setupCollectionView];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}

//找到导航栏最下面黑现实图
- (UIImageView *)getLineViewNavigationBar:(UIView *)view
{
    if ([view isKindOfClass:[UIImageView class]] && view.bounds.size.height <= 1.0f) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self getLineViewNavigationBar:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


-(void)classbtn{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请求添加为好友" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"发送",nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *nameField = [alert textFieldAtIndex:0];
    nameField.placeholder = @"请输入您的附加信息";
    nameField.keyboardType = UIKeyboardTypeDefault;
    
    [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
        if(buttonIndex == 1){
            UITextField *tf=[alert textFieldAtIndex:0];
            //if (tf.text.length > 0) {
                //token=验证用户&userId=用户id&userName=修改用户名&sex=性别&age=年龄&positionName=职位&shipUserId=上属用户id&shipUserType=上属用户类别&address=地址&mobile=联系电话
                NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
                [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
                [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
                [muDicParameters setObject:self.userId forKey:@"targetuserId"];
                [muDicParameters setObject:tf.text forKey:@"reason"];
                
                
                NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"isAddFriend_app_social.im.lensum"];
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                    //                    NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
                    //                                NSLog(@"--------------------json:%@",jsonStr);
                    
                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

                        [self showRightWithTitle:[dicInfo objectForKey:@"msg"] autoCloseTime:2];
                        
                        
                    }else {

                        [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                    }
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                   [self showSingleIconBubble:error.localizedDescription];
                    
                }];
                
            }
        //}
    }];

//    FriendViewController * FriendView = [[FriendViewController alloc]init];
//    FriendView.TagerUserId = self.userId;
//
//    [self.navigationController pushViewController:FriendView animated:YES];
    
}
#pragma mark - 私信
-(void)focus{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = NO;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = NO;
    
    sessionVC *chatVc = [[sessionVC alloc] init];
    if (self.dataDict[@"userName"]==nil || [self.dataDict[@"userName"] isEqualToString:@"null"] ||[self.dataDict[@"userName"] isEqualToString:@""]) {
        chatVc.title = self.dataDict[@"userName"][@"account"];
    }else{
        chatVc.title =self.dataDict[@"userName"];
    }
    chatVc.conversationType = ConversationType_PRIVATE;
    chatVc.targetId = self.dataDict[@"account"];
    chatVc.enableUnreadMessageIcon = YES;
    chatVc.enableNewComingMessageIcon = YES;
    chatVc.defaultHistoryMessageCountOfChatRoom = 50;
    
    self.tabBarController.tabBar.hidden = YES;
    
    [self.navigationController pushViewController:chatVc animated:YES];
}
//关注
-(void)rightBarButtonItemClick:(UIBarButtonItem *)sender{
        if (allConstMemberid) {
                self.isfocus = !self.isfocus;
        
                NSString *urlStr;
        
                NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                dic[@"userId"] = allConstMemberid;
                dic[@"token"] = allConstMemberToken;
                dic[@"targetUuserIid"] = self.userId;
        
                if (self.isfocus == NO) {
        
                    urlStr = @"focusUser_cannel_app_myHome.im.lensum";
        
                }else if (self.isfocus == YES){
        
                    urlStr = @"focusUser_app_myHome.im.lensum";
        
                }
        
                [LSHttpTool sendHttpData:urlStr params:dic success:^(id responseObject) {
        
                    if ([urlStr isEqualToString:@"focusUser_cannel_app_myHome.im.lensum"]) {
                        
                        [self.rightBtnItem setTitle:@"关注" forState:UIControlStateNormal];

                        
                    }else if ([urlStr isEqualToString:@"focusUser_app_myHome.im.lensum"]){
                        [self.rightBtnItem setTitle:@"已关注" forState:UIControlStateNormal];
        
                    }
        
                } failure:^(NSError *error) {
                    self.isfocus = !self.isfocus;

                    [self showSingleIconBubble:@"网络连接错误"];
        
                }];
        
            }else{
        
                UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
                [self presentViewController:loginNAV animated:YES completion:nil];
            }
    
}
-(void)leftBarButtonItemClick{
    FriendViewController * FriendView  = [[FriendViewController alloc]init];
    FriendView.TagerUserId = nil;
    
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setupCollectionView{
    
     UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
     layout.itemSize = CGSizeMake((screenW-1)/3 ,(screenW-1)/3);
    layout.sectionInset            = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumInteritemSpacing = 0.0;
    layout.minimumLineSpacing      = 0.0;
    
    UICollectionView *controller = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.topView.height + 64,screenW, screenH - self.topView.height - 64 - 35 - 10) collectionViewLayout:layout];

    controller.showsVerticalScrollIndicator = NO;
    controller.showsHorizontalScrollIndicator = NO;
    controller.contentSize = CGSizeZero;
    controller.contentSize = CGSizeMake(0, controller.height);
    controller.delegate = self;
    controller.dataSource = self;
    controller.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:controller];
    
    //集合头部的小线
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, self.topView.height + 64, screenW,1)];
    headView.backgroundColor = RGB(239, 239, 244);
    [self.view addSubview:headView];
    
    self.collectionview = controller;
    
    
}

#pragma mark - collection datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return  1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
         return self.imgArr.count ;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
 {

         
         UINib *nib = [UINib nibWithNibName:@"goveCell" bundle:nil];
         [self.collectionview registerNib:nib forCellWithReuseIdentifier:identifier];
         
         goveCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
         cell.img.image = [UIImage imageNamed:self.imgArr[indexPath.item]];
         
         return cell;
     

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;{
    
    areaEncyclopediasVC * areaVC = [[areaEncyclopediasVC alloc]init];
    goveNewsVC * govenewsVC = [[goveNewsVC alloc]init];
    projectLibraryVC * projectVC = [[projectLibraryVC alloc]init];
    TrickTender *trickTenderVC = [[TrickTender alloc] init];
    
    switch (indexPath.item) {
        case 0:
            areaVC.userId = self.userId;
            areaVC.type = @"1";
            [self.navigationController pushViewController:areaVC animated:YES];
            break;
            
        case 1:
            
            projectVC.userId = self.userId;
            
            [projectVC.navigationController.navigationBar.subviews.lastObject setHidden:YES];
            [self.navigationController pushViewController:projectVC animated:YES];
            
            break;
            
        case 2:
            govenewsVC.userId = self.userId;
            govenewsVC.titleStr = @"政府公报";
            [self.navigationController pushViewController:govenewsVC animated:YES];
            break;
            
        case 3:

            [self sendRequestWithChanYeUrlStr];
            break;
            
        case 4:
            govenewsVC.userId = self.userId;
            govenewsVC.titleStr = @"投资政策";
            [self.navigationController pushViewController:govenewsVC animated:YES];
            break;
            
        case 5:

            [self sendRequestWithTouZiUrlStr];
            break;
            
        case 6:

            [self sendRequestWithJiGouUrlStr];
            break;
            
            case 7:

            [self showSingleIconBubble:@"功能未开放"];
            
            break;
            
        case 8://招商投标
            trickTenderVC.userId = self.userId;
            [self.navigationController pushViewController:trickTenderVC animated:YES];
            break;
        
        case 9://商务动态
        {
            FriendViewController * FriendView = [[FriendViewController alloc]init];
            FriendView.TagerUserId = self.userId;
            
            [self.navigationController pushViewController:FriendView animated:YES];
        }
            break;
        default:
            break;
    }
    
    
}
#pragma mark - 请求数据
-(void)sendRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"userId"] = self.userId;
    dic[@"userType"] = self.userType;
    dic[@"address"] = self.addressStr;
    dic[@"MyUserId"] = allConstMemberid;
    
    [LSHttpTool sendHttpData:@"goveDetail_app_myHome.im" params:dic success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        _dataDict = dicInfo[@"data"];
        if ([_dataDict[@"isFocus"] isEqualToString:@"是"]) {
            
            [self.rightBtnItem setTitle:@"已关注" forState:UIControlStateNormal];
            self.isfocus = YES;
            
        }else{
            [self.rightBtnItem setTitle:@"关注" forState:UIControlStateNormal];
            self.isfocus = NO;
        }
        
        self.userId = _dataDict[@"userId"];
        
        if ([self.userId integerValue] == [allConstMemberid integerValue]) {
            self.navigationItem.rightBarButtonItem = nil;
        }
//        self.topView.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:177.0/255.0 blue:241.0/255.0 alpha:1];
        
//        [self.headImg.layer setCornerRadius:(self.headImg.frame.size.height/2)];
//        [self.headImg.layer setMasksToBounds:YES];
//        [self.headImg setContentMode:UIViewContentModeScaleAspectFill];
//        [self.headImg setClipsToBounds:YES];
//        self.headImg.layer.shadowColor = [UIColor blackColor].CGColor;
//        self.headImg.layer.shadowOffset = CGSizeMake(4, 4);
//        self.headImg.layer.shadowOpacity = 0.5;
//        self.headImg.layer.shadowRadius = 2.0;
//        self.headImg.userInteractionEnabled = YES;
//        [self.headImg sd_setImageWithURL:_dataDict[@"headPhoto"] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
        [self.headImg setImage:[UIImage imageNamed:@"20100403114758394_4147"]];
        self.goveName.text = _dataDict[@"userName"];
        if ([_dataDict[@"peopleNumber"] isEqualToString:@"null"]||[_dataDict[@"area"] isEqualToString:@"null"]) {
            self.goveDetail.text = @"";
        }else{
            self.goveDetail.text = [NSString stringWithFormat:@"人口%@  面积%@",_dataDict[@"peopleNumber"],_dataDict[@"area"]];
        }
        //        if ([dicInfo[@"data"][@"isFocus"] isEqualToString:@"是"]) {
//            self.focusBtn.selected = YES;
//        }else{
//            self.focusBtn.selected = NO;
//        }
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];
}

-(void)sendRequestWithChanYeUrlStr{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"userId"] = self.userId;
    
    [LSHttpTool sendHttpData:@"goveIndustryPlanning_app_myHome.im" params:dic success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        _webStr = dicInfo[@"data"][@"content"];
        newsDetailVC * newsVC = [[newsDetailVC alloc]init];
        newsVC.titleStr = @"产业规划";
        newsVC.urlStr = self.webStr;
        [self.navigationController pushViewController:newsVC animated:YES];

        [self showRightWithTitle:@"加载成功!" autoCloseTime:2];
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];

    }];
    
}
-(void)sendRequestWithTouZiUrlStr{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"userId"] = self.userId;
    
    [LSHttpTool sendHttpData:@"goveTouziyaosu_app_myHome.im" params:dic success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        _webStr = dicInfo[@"data"][@"content"];
        newsDetailVC * newsVC = [[newsDetailVC alloc]init];
        newsVC.titleStr = @"投资要素";
        newsVC.urlStr = self.webStr;
        [self.navigationController pushViewController:newsVC animated:YES];

        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];
    
}

-(void)sendRequestWithJiGouUrlStr{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"userId"] = self.userId;
    
    [LSHttpTool sendHttpData:@"goveServicejigou_app_myHome.im" params:dic success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        _webStr = dicInfo[@"data"][@"content"];
        newsDetailVC * newsVC = [[newsDetailVC alloc]init];
        newsVC.titleStr = @"服务机构";
        newsVC.urlStr = self.webStr;
        [self.navigationController pushViewController:newsVC animated:YES];

        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];
    
}
@end
